﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using IFDB.Models.Contexts;
using IFDB.Models.Foundation;
using IFDB.ResourceLibrary;

namespace IFDB.Models.Tables
{
    public class LookupMatch : BaseTable<LookupMatch>
    {
        [Key]
        public Guid LookupMatchId { get; set; }
        public Site Site { get; set; }

        [StringLength(25)]
        public string LookupId { get; set; }
        public Guid MatchId { get; set; }

        [ForeignKey("MatchId")]
        public virtual Match Match { get; set; }

        public static LookupMatch CreateNew(Site site, string lookupId, Guid matchId)
        {
            return new LookupMatch()
            {
                LookupMatchId = Guid.NewGuid(),
                Site = site,
                LookupId = lookupId,
                MatchId = matchId
            };
        }

        public static LookupMatch Update(LookupMatch lookupMatch, Site site, string lookupId, Guid matchId)
        {
            lookupMatch.Site = site;
            lookupMatch.LookupId = lookupId;
            lookupMatch.MatchId = matchId;

            return lookupMatch;
        }

        public static LookupMatch Search(IFDBContext db, Site site, string lookupId)
        {
            var localQuery = from lookupTeam in db.LookupMatches.Local
                             where lookupTeam.Site == site
                             && lookupTeam.LookupId == lookupId
                             select lookupTeam;

            var query = from lookupTeam in db.LookupMatches
                        where lookupTeam.Site == site
                        && lookupTeam.LookupId == lookupId
                        select lookupTeam;

            var search = ProcessSearch(localQuery, query, false);
            return search != null ? search.Single() : null;
        }
    }
}
